/////////////////////////////////////////////
/// Implementation of "WHERE IS * NOW"
/////////////////////////////////////////////
sparqlresult=""
//context.sendMessageToUser("ok, I'll try find out this.")

now = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date())
//context.sendMessageToUser(now)

// fetching the log
log = context.getLog()

// the wildcards
wildcard1 = match.wildcard(bitoflife.chatterbean.Match.Section.PATTERN,1).trim();

//FROM = "http://demo.ontowiki.net/model/export/?m=http%3A%2F%2Fbis.ontowiki.net%2F&output=xml"
//FROM = "http://sebastian.dietzold.de/rdf/foaf.rdf"
PREFIX = "PREFIX ical: <http://www.w3.org/2002/12/cal/ical#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
FromPart = "FROM <http://xmlns.com/foaf/spec/index.rdf> "

// where can we find infos about the subject
documentQuery = PREFIX + "SELECT DISTINCT ?document "+
//	FromPart+
	"WHERE{?s ?p1 ?subjectpattern. ?s rdfs:seeAlso ?document.\n"+
	"?document rdf:type ical:Vcalendar.\n"+
	"FILTER regex(?subjectpattern, '.*"+wildcard1+".*', 'i').}"
log.info(documentQuery)
//context.sendMessageToUser(documentQuery)

documents = context.queryForTable(documentQuery,["ontowiki"],null)
counter = 0;
FromNamedPart = ""
documents.each(){
	res = it
	counter = counter + res.getResultCount()
	log.info(res.getResultCount())
	res.getResultRows().each(){ 
		FromNamedPart += "FROM NAMED <${it["document"]}> \n"
		log.info(it["document"])
	}
}

if(counter < 1) context.sendMessageToUser("Sorry, I did not found any calendar in relation to '"+wildcard1+"'")
else{
  context.sendMessageToUser("I have found "+counter+" calendar documents which are in relation '"+wildcard1+"' ...")
	whereQuery = PREFIX + "SELECT DISTINCT ?location ?graph ?g ?summary\n"+
		FromNamedPart+
		"WHERE { GRAPH ?g { \n"+
		"?s ical:dtstart ?sbn. ?sbn ical:dateTime ?stime. \n"+
		"?s ical:dtend ?ebn. ?ebn ical:dateTime ?etime. \n"+
		"?s ical:location ?location. \n"+
		"?s ical:summary ?summary. \n"+
		"FILTER (?stime < '"+now+"') \n"+
		"FILTER (?etime > '"+now+"') \n"+
		"} OPTIONAL {?g rdfs:label ?graph} }"

	//context.sendMessageToUser(whereQuery)
	locations = context.queryForTable(whereQuery,["generic"],null)
	counter = 0;
	locations.each(){
		res = it
		counter = counter + res.getResultCount()
		log.info(res.getResultCount())
		res.getResultRows().each(){ 
			log.info(it["location"])
			context.sendMessageToUser(it["location"] + " (summary: " + it["summary"] + ")")
		}
	}
}

